package fy.hr.operator.impl;

import java.util.Hashtable;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.services.ServiceException;
import com.seeyon.v3x.services.V3XLocator;
import com.seeyon.v3x.services.flow.bean.FlowExport;
import com.sun.codemodel.JVar;

import fy.form.listen.operate.AForm_Save_Operator;
import fy.form.listen.operate.IFormOperator;
import fy.hr.bean.LeaveFormBean;
import fy.hr.constant.OA2HRConstant;
import fy.hr.dao.LeaveForm_Elimination_Dao;
import fy.hr.dao.LeaveForm_WriterDao;
import fy.msg.MessageSender;
import fy.util.MyUtil;

public class LeaveFormOperator extends AForm_Save_Operator implements
        IFormOperator {

    private static Log log = LogFactory.getLog(LeaveFormOperator.class);

    private LeaveFormBean bean = new LeaveFormBean();

    private static final Map<String, String> LEAVE_TYPE_MAP = new Hashtable<String, String>();

    private String leaveType;

    private String title;
    private String xinchou;

    static {
        LEAVE_TYPE_MAP.put("0", "事假");
        LEAVE_TYPE_MAP.put("1", "病假");
        LEAVE_TYPE_MAP.put("2", "产假");
        LEAVE_TYPE_MAP.put("3", "婚假");
        LEAVE_TYPE_MAP.put("4", "丧假");
        LEAVE_TYPE_MAP.put("6", "工伤");
        LEAVE_TYPE_MAP.put("7", "年假");
        LEAVE_TYPE_MAP.put("8", "销假");
        LEAVE_TYPE_MAP.put("9", "调休");
        LEAVE_TYPE_MAP.put("11", "无单假");
        LEAVE_TYPE_MAP.put("13", "公休假补休");
        LEAVE_TYPE_MAP.put("14", "返校假");
        LEAVE_TYPE_MAP.put("15", "陪产假");
        LEAVE_TYPE_MAP.put("16", "独生子女护理假");
    }

    public String getFormName() {
        return "请假条";
    }

    public boolean save() {
        boolean success = false;
        String msg = null;
        try {
            if (bean.getLeaveType() == null) {
                msg = new StringBuilder().append("请假条《").append(this.title)
                        .append("》请假类型为：")
                        .append("8".equals(leaveType) ? "销假" : "无法匹配的假别")
                        .append("，无法由系统自动写入HR。单据编号为：")
                        .append(bean.getFormNumber()).append("，请假人工号：")
                        .append(bean.getMemberCode()).toString();
                sendMessage(msg);
                log.warn(msg);
                success = true;
            } else {
                // 判断用户请假日期，截止时间是否比初始日期大
                if (!MyUtil.later(
                        new StringBuilder()
                        .append(MyUtil.getDate(bean.getStartDate()))
                        .append(" ")
                        .append(MyUtil.getDate(bean.getStartTime()))
                        .toString(),
                        new StringBuilder()
                        .append(MyUtil.getDate(bean.getEndDate()))
                        .append(" ")
                        .append(MyUtil.getDate(bean.getEndTime()))
                        .toString())) {
                    if (!"8".equals(leaveType)) {
                        LeaveForm_WriterDao dao = new LeaveForm_WriterDao();
                        dao.setLeaveBean(bean);
                        if (dao.write(String.valueOf(V3XLocator.getInstance().lookup(ColManager.class).getSummaryById(Long.valueOf(bean.getSummaryId())).getOrgAccountId()))) {
                            success = true;
                            if (dao.isNeedRecord()) {
                                msg = new StringBuilder().append("请假条《")
                                        .append(this.title).append("》请假类型为：")
                                        .append(bean.getLeaveType())
                                        .append("，警告:")
                                        .append(dao.getErrorMsg())
                                        .append("。单据编号为：")
                                        .append(bean.getFormNumber())
                                        .append("，请假人工号：")
                                        .append(bean.getMemberCode())
                                        .toString();
                                sendMessage(msg);

                                log.warn(msg);
                            } else {
                                log.info(new StringBuilder().append("请假条《")
                                        .append(this.title).append("》请假类型为：")
                                        .append(bean.getLeaveType())
                                        .append("写入HR成功。单据编号为：")
                                        .append(bean.getFormNumber())
                                        .append("，请假人工号：")
                                        .append(bean.getMemberCode())
                                        .toString());
                            }
                        } else {
                            // 是否要写入日志，因为用户不存在考勤档案的原因，写入失败，不写入日志
                            success = !dao.isNeedRecord();
                            msg = new StringBuilder().append("请假条《")
                                    .append(this.title).append("》请假类型为：")
                                    .append(bean.getLeaveType())
                                    .append("，写入HR发生异常：")
                                    .append(dao.getErrorMsg())
                                    .append("。单据编号为：")
                                    .append(bean.getFormNumber())
                                    .append("，请假人工号：")
                                    .append(bean.getMemberCode()).toString();
                            sendMessage(msg);

                            log.warn(msg);
                        }
                        dao = null;
                    } else {
                        LeaveForm_Elimination_Dao dao = new LeaveForm_Elimination_Dao();
                        dao.setLeaveBean(bean);
                        if (dao.write(String.valueOf(V3XLocator.getInstance().lookup(ColManager.class).getSummaryById(Long.valueOf(bean.getSummaryId())).getOrgAccountId()))) {
                            success = true;
                            log.info(new StringBuilder().append("请假条《")
                                    .append(this.title).append("》请假类型为：")
                                    .append(bean.getLeaveType())
                                    .append("写入HR成功。单据编号为：")
                                    .append(bean.getFormNumber())
                                    .append("，请假人工号：")
                                    .append(bean.getMemberCode()).toString());
                        } else {
                            msg = new StringBuilder().append("请假条《")
                                    .append(this.title)
                                    .append("》请假类型为：销假，写入HR发生异常：")
                                    .append(dao.getErrorMsg())
                                    .append("。单据编号为：")
                                    .append(bean.getFormNumber())
                                    .append("，请假人工号：")
                                    .append(bean.getMemberCode()).toString();
                            sendMessage(msg);
                            // MessageSender.sendMsg(, msg);
                            log.warn(msg);
                        }
                        dao = null;
                    }
                } else {
                    msg = new StringBuilder().append("请假条《").append(this.title)
                            .append("》请假类型为：").append(bean.getLeaveType())
                            .append("，错误提示：假期截止日期比起始日期小。单据编号为：")
                            .append(bean.getFormNumber()).append("，请假人工号：")
                            .append(bean.getMemberCode()).toString();
                    sendMessage(msg);
                    success = true;
                    log.warn(msg);
                }
            }

            return success;
        } catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            msg = null;
        }
        return false;
    }

    @Override
    protected void parseOtherField_FirstStep(FlowExport flowExport) {
        bean.setSummaryId(String.valueOf(super.formBean.getSummaryId()));
        title = flowExport.getFlowTitle();
    }

    @Override
    protected void parseValueExport(
            com.seeyon.v3x.services.form.bean.ValueExport ve) {
        String name = ve.getDisplayName();
        String value = ve.getValue();
        if ("表单编号".equals(name)) {
            bean.setFormNumber(value);
        } else if ("日期".equals(name)) {
            bean.setApplicationDate(MyUtil.getDate(value));
        } else if ("工号".equals(name)) {
            bean.setMemberCode(value);
        } else if ("请假人电话".equals(name)) {
            bean.setTel(value);
        } else if ("假别".equals(name)) {
            leaveType = value;
//            System.err.println("类别："+leaveType);
            bean.setLeaveType(LEAVE_TYPE_MAP.get(leaveType));
        } else if ("请假说明".equals(name)) {
            bean.setReason(value == null ? "" : value);
        } else if ("起日期".equals(name)) {
            bean.setStartDate(MyUtil.getDate(value));
        } else if ("起时间".equals(name)) {
            bean.setStartTime(OA2HRConstant.START_WORK_TIME["0".equals(value) ? 0
                    : 1]);
        } else if ("止日期".equals(name)) {
            bean.setEndDate(MyUtil.getDate(value));
        } else if ("止时间".equals(name)) {
            bean.setEndTime(OA2HRConstant.END_WORK_TIME["0".equals(value) ? 0
                    : 1]);
        } else if ("请假天数1".equals(name)) {
            bean.setLeaveDays(value);
        } else if ("薪酬".equals(name)) {
            xinchou = (isLong(value) ? value : (isLong(ve.getDisplayValue()) ? ve.getDisplayValue() : null));
        }
        name = null;
        value = null;
    }

    private boolean isLong(String s) {
        if (MyUtil.strIsNotNull(s)) {
            try {
                Long.valueOf(s);
                return true;
            } catch (NumberFormatException e) {
            }
        }
        return false;
    }

    private void sendMessage(String msg) {
        if (xinchou != null) {
            MessageSender.sendMsg(new long[]{super.createPerson.getId(), Long.valueOf(xinchou)}, msg);
        } else {
            MessageSender.sendMsg(new long[]{super.createPerson.getId(), super.formBean.getOperatorID()}, msg);
        }
    }
}
